"""
A twisted.web resource script demonstrating detection of mobile devices.

Please do be so kind as to overlook the fact that handsetdetection does not use
Twisted's twisted.web.client to make HTTP requests, so handsetdetection API
calls block the twisted reactor.  This is only for testing purposes.
"""
# Copyright (c) 2013 Teleport Corp Pty Ltd.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

# Written by Troy Farrell <troy@entheossoft.com>
# Created: 20130118

import cgi

import handsetdetection
import twisted.python.log
import twisted.web.resource

class MyHDResource(twisted.web.resource.Resource):
    """
    A twisted.web resource that uses Handsetdetection.com
    """

    def get_client_and_server_data(self, request):
        "Get environment data."
        data = {}
        data["HTTP_REFERER"] = request.getHeader("referer") or ''
        data["HTTP_USER_AGENT"] = request.getHeader("user-agent") or ''
        data["REMOTE_ADDR"] = request.getClient() or ''
        data["REQUEST_URI"] = request.uri or ''
        data["SERVER_ADDR"] = request.host.host or ''
        data["SERVER_PORT"] = request.host.port or ''
        data["SERVER_NAME"] = request.getRequestHostname() or ''
        return data

    def welcome(self, data):
        "Return a response to the browser."
        if data is None:
            display = "<p>Your device is not a mobile device.</p>"
        else:
            c2c = repr(data.get_click_to_call())
            sms = repr(data.get_send_sms())
            display = """<dl>
    <dt>Click to call string</dt>
        <dd>%s</dd>
    <dt>Send SMS string</dt>
        <dd>%s</dd>
</dl>""" % tuple([cgi.escape(string) for string in (c2c, sms)])

        result = """Content-type: text/html;charset=UTF-8

<!DOCTYPE html>
<html>
    <head>
        <title>Welcome to our web site</title>
        <meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
    </head>
    <body>
        %s
    </body>
</html>""" % display
        return result


    def render(self, request):
        # First, get the information to pass to Handset Detection.
        hd = handsetdetection
        hd.set_credentials("demo@handsetdetection.com", "demo")
        data = self.get_client_and_server_data(request)
        try:
            result = hd.detect(data, "xhtml_ui")
            return self.welcome(result)
        except handsetdetection.DeviceNotFoundError, err:
            # Mobile device not detected.
            return self.welcome(None)

resource = MyHDResource()

# vim:set et sw=4 ts=4 tw=79:
